package com.bobbygu.bobbyapp.function

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.view.View
import com.bobbygu.bobbyapp.R
import com.bobbygu.lib.mvvm.common.BaseActivity
import com.bobbygu.lib.mvvm.common.BaseModel
import com.bobbygu.lib.mvvm.common.BaseViewModel
import android.text.TextUtils
import kotlinx.android.synthetic.main.activity_tts.*
import android.speech.tts.TextToSpeech
import android.util.Log
import android.widget.Toast
import cn.jpush.android.api.JPushInterface
import com.bobbygu.bobbyapp.function.xmpp.LocalBroadcastManager
import com.bobbygu.libspeech.Speecher
import com.bobbygu.libspeech.TtsDemo
import com.orhanobut.logger.Logger
import java.util.*


/**
 *
 * # time: 2018/1/31 12:07
 * # e-mail: gubojun@csii.com.cn
 * @author 顾博君
 * @since 1.0
 */
@Suppress("FINITE_BOUNDS_VIOLATION_IN_JAVA")
class TTSActivity<VM : BaseViewModel<*, *>, M : BaseModel<*>> : BaseActivity<VM, M>() {
    private var mSpeech: TextToSpeech? = null
    private val TAG_TTS = "TTSActivity"
    private var mMessageReceiver: MessageReceiver? = null
    override fun getLayoutId() = R.layout.activity_tts

    override fun initView() {
        registerMessageReceiver()
        init()
    }

    private fun registerMessageReceiver() {
        mMessageReceiver = MessageReceiver()
        val filter = IntentFilter()
        filter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY
        filter.addAction(MESSAGE_RECEIVED_ACTION)
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter)
    }

    inner class MessageReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            try {
                Logger.d("MessageReceiver")
                if (MESSAGE_RECEIVED_ACTION == intent.action) {
                    val messge = intent.getStringExtra(KEY_MESSAGE)
                    val extras = intent.getStringExtra(KEY_EXTRAS)
                    val alert = intent.getStringExtra(KEY_ALERT)
//                    val showMsg = StringBuilder()
//                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n")
//                    if (!TextUtils.isEmpty(extras)) {
//                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n")
//                    }
                    Logger.d("msg:" + alert)
                }
            } catch (e: Exception) {
            }
        }
    }

    private fun init() {
        speechInit()
    }

    fun toSpeak(view: View) {
        var text = et_input.text.toString()
        if (TextUtils.isEmpty(text)) text = "请输入要测试的内容"
        playTTS(text)
    }

    var chinese = true
    fun change(view: View) {
        val intent = Intent(this@TTSActivity, TtsDemo::class.java)
        startActivity(intent)
        if (chinese) {
            chinese = false
            speechInit2()
            btn_open_wifi.text = "英文"
        } else {
            chinese = true
            speechInit()
            btn_open_wifi.text = "中文"
        }
    }


    private fun speechInit() {
        if (mSpeech != null) {
            mSpeech?.stop()
            mSpeech?.shutdown()
            mSpeech = null
        }
        // 创建TTS对象
        mSpeech = TextToSpeech(this@TTSActivity, TTSListener())
    }

    private fun speechInit2() {
        if (mSpeech != null) {
            mSpeech?.stop()
            mSpeech?.shutdown()
            mSpeech = null
        }
        // 创建TTS对象
        mSpeech = TextToSpeech(this@TTSActivity, TTSListener2())
    }

    /**
     * 将文本用TTS播放
     *
     * @param str 播放的文本内容
     */
    private fun playTTS(str: String) {
        mSpeech?.setPitch(0f)
        mSpeech?.speak(str, TextToSpeech.QUEUE_FLUSH, null)
        Log.i(TAG_TTS, "播放语音为：" + str)
    }

    private inner class TTSListener : TextToSpeech.OnInitListener {
        override fun onInit(status: Int) {
            Log.e(TAG_TTS, "初始化结果：" + (status == TextToSpeech.SUCCESS))
            val result = mSpeech?.setLanguage(Locale.CHINESE)
            //如果返回值为-2，说明不支持这种语言
            Log.e(TAG_TTS, "是否支持该语言：" + (result != TextToSpeech.LANG_NOT_SUPPORTED))
        }
    }

    private inner class TTSListener2 : TextToSpeech.OnInitListener {
        override fun onInit(status: Int) {
            Log.e(TAG_TTS, "初始化结果：" + (status == TextToSpeech.SUCCESS))
            val result = mSpeech?.setLanguage(Locale.US)
            //如果返回值为-2，说明不支持这种语言
            Log.e(TAG_TTS, "是否支持该语言：" + (result != TextToSpeech.LANG_NOT_SUPPORTED))
        }
    }

    override fun onDestroy() {
        if (mSpeech != null) {
            mSpeech?.stop()
            mSpeech?.shutdown()
            mSpeech = null
        }
        super.onDestroy()
    }


    companion object {
        val MESSAGE_RECEIVED_ACTION = "com.bobbygu.bobbyapp.MESSAGE_RECEIVED_ACTION"
        val KEY_TITLE = "title"
        val KEY_MESSAGE = "message"
        val KEY_EXTRAS = "extras"
        val KEY_ALERT = "alert"
        /**
         * @param activity BaseActivity
         */
        fun startActivity(activity: BaseActivity<*, *>) {
            activity.startActivity(TTSActivity::class.java)
        }
    }
}